<template>
  <div class="user-management">
    <div class="card">
      <div class="card-header flex-between">
        <span>用户列表</span>
        <button @click="showAddModal = true" class="btn">+ 添加用户</button>
      </div>

      <!-- 搜索框 -->
      <div class="search-bar">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="🔍 搜索用户名、邮箱、姓名..."
          class="search-input"
          @input="handleSearch"
        />
        <span v-if="searchQuery" class="search-clear" @click="clearSearch">✕</span>
        <span class="search-info">共找到 {{ filteredUsers.length }} 个用户</span>
      </div>

      <div v-if="loading" class="text-center p-2">
        <div class="loading"></div>
      </div>

      <table v-else>
        <thead>
          <tr>
            <th>用户名</th>
            <th>邮箱</th>
            <th>姓名</th>
            <th>状态</th>
            <th>角色</th>
            <th>SSH权限</th>
            <th>加入时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="filteredUsers.length === 0">
            <td colspan="8" class="text-center no-data">
              {{ searchQuery ? '没有找到匹配的用户' : '暂无用户数据' }}
            </td>
          </tr>
          <tr v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.username }}</td>
            <td>{{ user.email || '-' }}</td>
            <td>{{ user.first_name }} {{ user.last_name }}</td>
            <td>
              <span :class="['badge', user.is_active ? 'badge-online' : 'badge-offline']">
                {{ user.is_active ? '激活' : '禁用' }}
              </span>
            </td>
            <td>
              <span v-if="user.is_superuser" class="badge badge-danger">超级管理员</span>
              <span v-else-if="user.is_staff" class="badge badge-warning">管理员</span>
              <span v-else class="badge badge-info">普通用户</span>
            </td>
            <td>
              <span v-if="user.can_use_ssh" class="badge badge-success">✓ 允许</span>
              <span v-else class="badge badge-secondary">✗ 禁止</span>
            </td>
            <td>{{ formatDate(user.date_joined) }}</td>
            <td>
              <div class="flex gap-1">
                <button @click="editUser(user)" class="btn" style="padding: 4px 8px; font-size: 10px;">编辑</button>
                <button @click="openChangePasswordModal(user)" class="btn btn-warning" style="padding: 4px 8px; font-size: 10px;">改密码</button>
                <button v-if="!user.is_superuser" @click="deleteUser(user.id)" class="btn btn-danger" style="padding: 4px 8px; font-size: 10px;">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ showEditModal ? '编辑用户' : '添加用户' }}</h2>
          <button @click="closeModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label>用户名 *</label>
              <input v-model="formData.username" type="text" required />
            </div>
            <div class="form-group">
              <label>邮箱</label>
              <input v-model="formData.email" type="email" />
            </div>
            <div class="form-group">
              <label>名</label>
              <input v-model="formData.first_name" type="text" />
            </div>
            <div class="form-group">
              <label>姓</label>
              <input v-model="formData.last_name" type="text" />
            </div>
            <div v-if="!showEditModal" class="form-group">
              <label>密码 *</label>
              <input v-model="formData.password" type="password" required placeholder="请输入密码（最少6位）" />
            </div>
            <div v-if="!showEditModal" class="form-group">
              <label>确认密码 *</label>
              <input v-model="formData.confirmPassword" type="password" required placeholder="再次输入密码" />
            </div>
            <div class="form-group">
              <label>
                <input v-model="formData.is_active" type="checkbox" />
                激活状态
              </label>
            </div>
            <div class="form-group">
              <label>
                <input v-model="formData.is_staff" type="checkbox" />
                管理员权限
              </label>
            </div>
            <div v-if="currentUser?.is_superuser && showEditModal" class="form-group">
              <label>
                <input v-model="formData.can_use_ssh" type="checkbox" />
                SSH访问权限
              </label>
              <small class="text-muted">允许用户使用SSH终端功能</small>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="closeModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordModal" class="modal" @click.self="closePasswordModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>🔐 修改密码 - {{ passwordForm.username }}</h2>
          <button @click="closePasswordModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="changePassword">
            <div class="form-group">
              <label>新密码 *</label>
              <input v-model="passwordForm.new_password" type="password" required placeholder="请输入新密码（最少6位）" />
            </div>
            <div class="form-group">
              <label>确认新密码 *</label>
              <input v-model="passwordForm.confirm_password" type="password" required placeholder="再次输入新密码" />
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">确认修改</button>
              <button type="button" @click="closePasswordModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '../services/api'

const users = ref([])
const loading = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showPasswordModal = ref(false)
const currentUser = ref(null)
const searchQuery = ref('')

const formData = ref({
  username: '',
  email: '',
  first_name: '',
  last_name: '',
  is_active: true,
  is_staff: false,
  can_use_ssh: false,
  password: '',
  confirmPassword: ''
})

const passwordForm = ref({
  userId: null,
  username: '',
  new_password: '',
  confirm_password: ''
})

// 过滤用户列表
const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return users.value
  }
  
  const query = searchQuery.value.toLowerCase().trim()
  
  return users.value.filter(user => {
    // 搜索用户名
    if (user.username && user.username.toLowerCase().includes(query)) {
      return true
    }
    // 搜索邮箱
    if (user.email && user.email.toLowerCase().includes(query)) {
      return true
    }
    // 搜索姓名
    const fullName = `${user.first_name || ''} ${user.last_name || ''}`.toLowerCase()
    if (fullName.includes(query)) {
      return true
    }
    return false
  })
})

onMounted(() => {
  fetchUsers()
  fetchCurrentUser()
})

const fetchCurrentUser = async () => {
  try {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      currentUser.value = JSON.parse(storedUser)
    }
  } catch (error) {
    console.error('获取当前用户失败:', error)
  }
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await api.getUsers()
    users.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch users:', error)
  } finally {
    loading.value = false
  }
}

const editUser = (user) => {
  formData.value = {
    ...user,
    can_use_ssh: user.can_use_ssh || false
  }
  showEditModal.value = true
}

const saveUser = async () => {
  try {
    if (showEditModal.value) {
      await api.updateUser(formData.value.id, formData.value)
    } else {
      // 添加用户时验证密码
      if (!formData.value.password || formData.value.password.length < 6) {
        alert('密码长度不能少于6位')
        return
      }
      if (formData.value.password !== formData.value.confirmPassword) {
        alert('两次输入的密码不一致')
        return
      }
      await api.createUser(formData.value)
    }
    await fetchUsers()
    closeModal()
  } catch (error) {
    console.error('Failed to save user:', error)
    alert('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteUser = async (id) => {
  if (!confirm('确定要删除这个用户吗?')) return
  try {
    await api.deleteUser(id)
    await fetchUsers()
  } catch (error) {
    console.error('Failed to delete user:', error)
    alert('删除失败: ' + (error.response?.data?.detail || error.message))
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    username: '',
    email: '',
    first_name: '',
    last_name: '',
    is_active: true,
    is_staff: false,
    can_use_ssh: false,
    password: '',
    confirmPassword: ''
  }
}

// 打开修改密码弹窗
const openChangePasswordModal = (user) => {
  passwordForm.value = {
    userId: user.id,
    username: user.username,
    new_password: '',
    confirm_password: ''
  }
  showPasswordModal.value = true
}

// 关闭修改密码弹窗
const closePasswordModal = () => {
  showPasswordModal.value = false
  passwordForm.value = {
    userId: null,
    username: '',
    new_password: '',
    confirm_password: ''
  }
}

// 修改密码
const changePassword = async () => {
  if (passwordForm.value.new_password.length < 6) {
    alert('密码长度不能少于6位')
    return
  }
  if (passwordForm.value.new_password !== passwordForm.value.confirm_password) {
    alert('两次输入的密码不一致')
    return
  }
  
  try {
    await api.changeUserPassword(passwordForm.value.userId, {
      password: passwordForm.value.new_password
    })
    alert('密码修改成功！')
    closePasswordModal()
  } catch (error) {
    console.error('修改密码失败:', error)
    alert('修改密码失败: ' + (error.response?.data?.error || error.message))
  }
}

// 搜索处理（实际上使用computed已经自动处理了）
const handleSearch = () => {
  // filteredUsers 会自动更新
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-bg-secondary);
  border: 2px solid var(--color-accent-cyan);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 2px solid var(--color-border);
}

.modal-header h2 {
  color: var(--color-accent-cyan);
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 18px;
}

.modal-close {
  background: transparent;
  border: none;
  color: var(--color-accent-red);
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-group label input[type="checkbox"] {
  width: auto;
  margin-right: 8px;
}

.text-muted {
  display: block;
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
  margin-top: 4px;
}

.badge-info {
  background: rgba(33, 150, 243, 0.2);
  color: #2196f3;
  border: 1px solid #2196f3;
}

.badge-success {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
  border: 1px solid #4caf50;
}

.badge-secondary {
  background: rgba(158, 158, 158, 0.2);
  color: #9e9e9e;
  border: 1px solid #9e9e9e;
}

.badge-danger {
  background: rgba(244, 67, 54, 0.2);
  color: #f44336;
  border: 1px solid #f44336;
}

/* 搜索框样式 */
.search-bar {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-bottom: 2px solid var(--color-border);
  position: relative;
}

.search-input {
  flex: 1;
  padding: 12px 40px 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border: 2px solid rgba(255, 70, 85, 0.3);
  border-radius: 8px;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: var(--color-accent-red);
  box-shadow: 0 0 0 3px rgba(255, 70, 85, 0.1);
  background: rgba(255, 255, 255, 0.08);
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.4);
}

.search-clear {
  position: absolute;
  right: 190px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 70, 85, 0.2);
  border-radius: 50%;
  color: var(--color-accent-red);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.search-clear:hover {
  background: rgba(255, 70, 85, 0.4);
  transform: translateY(-50%) scale(1.1);
}

.search-info {
  min-width: 150px;
  text-align: right;
  color: var(--color-accent-cyan);
  font-size: 13px;
  font-weight: 600;
  padding: 8px 16px;
  background: rgba(0, 255, 200, 0.1);
  border: 1px solid rgba(0, 255, 200, 0.3);
  border-radius: 6px;
}

.no-data {
  padding: 40px 20px !important;
  text-align: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
}

@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-clear {
    right: 20px;
  }
  
  .search-info {
    text-align: center;
  }
}
</style>
